package com.SmartCare.controller.common;

import com.SmartCare.common.Result;
import com.SmartCare.mapper.role.UserMapper;
import com.SmartCare.pojo.reminder.AlarmParams;
import com.SmartCare.pojo.role.User;
import com.SmartCare.utils.SignUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/wx")
@Api(tags = "WX服务接口")
@Slf4j
public class WXController {

    private String appid = "wxd7705602062b43f8";

    private String secret = "d3e223a99f1cc0bd6492e296e391db29";

    @Resource
    private UserMapper userMapper;

    @GetMapping("/auth")
    public void authPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(request.getParameter("signature"))) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                response.getOutputStream().println(echostr);
            }
        }
    }

    @GetMapping("/send")
    public Result sendTest() {
        User user = userMapper.selectById("1736365166976630786");
        AlarmParams alarmParams = AlarmParams.builder()
                .thing3(user.getName())
                .thing4("测试消息")
                .thing5("通话提醒")
                .build();
        //发送消息
        sendMsg(user, alarmParams);
        return Result.success();
    }

    /**
     * 向指定用户推送公众号消息
     *
     * @param user        用户对象
     * @param alarmParams 消息参数对象
     */
    public void sendMsg(User user, AlarmParams alarmParams) {


        String openId = user.getOpenid();
        //向该用户发送消息

        //1 配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(appid);
        wxStorage.setSecret(secret);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        List<WxMpTemplateData> wxMpTemplateData = Arrays.asList(
                new WxMpTemplateData("thing3", alarmParams.getThing3()),
                new WxMpTemplateData("thing4", alarmParams.getThing4()),
                new WxMpTemplateData("thing5", alarmParams.getThing5())
        );
        //2 推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("8om3bWHIU4L_-xJWR4OnTyKAK_H7DMR2Fq_24jxR_uo")
                .data(wxMpTemplateData)
                .build();
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
        }
    }
}


